<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\Backend;
use hg\apidoc\annotation as Apidoc;
use think\facade\Db;

/**
 * 应用管理
 * @Apidoc\Group("base")
 * @package app\admin\controller
 */
class App extends Backend
{
    /**
     * 初始化参数
     * @author 贾二小
     * @since 2021/7/3
     */
    public function initialize()
    {
        $this->config = [
            'name'=>'应用管理',
            'table_name'=>'app',//表名
            'table_alias' => 'a',//别名
            'table_field'=>'*',//显示默认字段
            'form_field' => 'id,name,code,active,status,remark',//表单字段，没有设置则默认为显示字段默认是不能有*和.)
            'form_validated1' => [
                'name' => ['msg' => '名称为空', 'regex' => false, 'pcre' => '',],
                'code' => ['msg' => 'code为空', 'regex' => false, 'pcre' => '',],
            ],//表单验证
            'form_validated2' => ['code'],//重复验证
            'search_table'=> null,//关联表时，需要重写
            'is_limit'=> true,//是否分页显示
            'search_field' => 'id,name,code,active,status,remark,create_user_id,create_date,update_user_id,update_date',//查询表格字段
            'search_param'=>[
                ['field' => 'name', 'type' => '=', 'param'=> 'name'],
                ['field' => 'code', 'type' => '=', 'param'=> 'code'],
            ],//查询表格条件
            'is_delete'=> true,//是否假删除
            'id_validated' => [
                'id' => ['msg' => 'ID不能为空', 'regex' => false, 'pcre' => '', 'regex_msg'=>'', 'db'=>true, 'db_msg'=>'当前应用不存在'],
            ],//表单验证
        ];
        parent::initialize();
    }

    /**
     * @Apidoc\Title("设置默认应用")
     * @Apidoc\Desc("设置默认显示的应用")
     * @Apidoc\Url("/admin/app/set_as_default")
     * @Apidoc\Method("POST")
     * @Apidoc\Tag("测试 基础")
     * @Apidoc\Param("id", type="int",default="0",desc="应用ID" )
     * @author 贾二小
     * @since 2021/7/10
     */
    public function set_as_default(){
        //获取参数
        $id = intval(input('id'));
        //数据验证
        $this->form_validated('id_validated');
        //数据组装
        $data = [];
        $data['active'] = 'N';
        $data['update_user_id'] = _current_user('id');
        //数据库操作
        Db::transaction(function () use ($id, $data) {
            //删除所有默认
            Db::name($this->config['table_name'])->where(['active'=>'Y','is_delete'=>0])->update($data);
            //默认当前数据
            $data['active'] = 'Y';
            Db::name($this->config['table_name'])->where(['id'=>$id])->update($data);
        });
        //日志
        $this->sLog($this->config['name'].'_设为默认应用',"成功");
        //返回
        $this->success();
    }
}